import tkinter as tk
import tkinter.messagebox as messagebox
import time
import math

class CrcCalculationDetailsFrame(tk.Frame):

    def update(self, crc):
            for i in range(0, self.polynomLength+1):
                self.crc[i].set(crc[i])
    def create_help_button(self):
        """Create the help button."""
        def display_help():
            text = """In this section, you can see the details of the crc calculation.

Press the "1 step" button to progress of one step in the calculation.
This will run the algorithm with one bit of data.
Pressing "auto step" will step twice a second, so that the process can
be seen without having to repeatedly press "1 step".
You can stop the automatical steping at any time by pressing the 
"Stop auto step" button.

Note that in verbose mode, the calculated CRC will be displayed
as a polynom (x**2+1). If you hoover over it, the copyable text
will however still be zeroes and ones."""
            messagebox.showinfo('Help', text)
        self.help_button = tk.Button(self, text='?', command=display_help)
        self.help_button.place(in_=self,anchor=tk.N+tk.E,relx=1,x=-5,y=5)

    def create_widgets(self, polynom):
        
        polynomLength = int(math.log(polynom, 2))
        
        self.delete_widgets()
        
        self.autorun = False
        
        self.crcOut.set(" ")
        
        self.polynomLength = polynomLength
        self.crcOutLabel = tk.Label(self.centeredFrame, textvariable=self.crcOut, height=2, width=5)
        self.crcOutLabel.grid(column = 0, row = 1)
        self.crcLabels = []
        self.polynomLabels = []
        self.crc = []
        self.timeLastStep = time.time()
        nFactor = 0

        for i in range(0, polynomLength+1):
            self.crc.append(tk.StringVar())
            self.crc[i].set(" ")
            if i == polynomLength:
                self.crcLabels.append(tk.Label(self.centeredFrame, textvariable=self.crc[i], height=2, width=5))
            else:
                self.crcLabels.append(tk.Label(self.centeredFrame, textvariable=self.crc[i], height=2, width=5, relief="ridge", bd=2))
            self.crcLabels[i].grid(column = i+1, row = 1)
            
            self.centeredFrame.columnconfigure(i, minsize=20)
            if bin(polynom)[i+2] == bin(1)[2]:
                if i == polynomLength:
                    currentLabel = tk.Label(self.centeredFrame, text="1")
                else:
                    currentLabel = tk.Label(self.centeredFrame, text=("x**"+str((polynomLength-i))))
                self.polynomLabels.append(currentLabel)
                if i > 0:
                    self.crcLabels[i-1]["bg"] = "#a0a0a0"
                self.polynomLabels[nFactor].grid(column=i+1, row=0)
                nFactor = nFactor+1

        self.buttonFrame = tk.Frame(self.centeredFrame)
        self.buttonFrame.grid(row = 2, column = 0, columnspan=int(polynomLength+2), pady = 10)
        
        self.stepButton = tk.Button(self.buttonFrame, text='1 step', command = self.nextLoop, width = 14)
        self.stepButton.grid(column=0, row=0, padx=10)

        self.runButton = tk.Button(self.buttonFrame, text='Auto step', command = self.autorunOn, width = 14)
        self.runButton.grid(column=1, row=0, padx=10)

        self.stopButton = tk.Button(self.buttonFrame, text='Stop auto step', command = self.autorunOff, width = 14)
        self.stopButton.grid(column=2, row=0, padx=10)
        
        self.lock = True
        self.widgets = True

    def nextLoop(self):
        self.crcOut.set(self.crc[0].get())
        self.lock = False

    def autorunOn(self):
        if not self.autorun:
            self.timeLastStep = time.time()
        self.autorun = True

    def autorunOff(self):
        self.autorun = False

    def delete_widgets(self):
        if self.widgets:          
            for label in self.crcLabels:
                label.destroy()
            for label in self.polynomLabels:
                label.destroy()
            self.buttonFrame.destroy()
            self.stepButton.destroy()
            self.runButton.destroy()
            self.stopButton.destroy()
            self.crcLabels = []
            self.polynomLabels = []
            self.crc = []
            self.widgets = False

    def init_centeredFrame(self):
        self.centeredFrame = tk.Frame(self)
        self.centeredFrame.pack(anchor = tk.CENTER, padx = 25, pady = 10)
        self.centeredFrame.rowconfigure(0, minsize=20)
        self.centeredFrame.rowconfigure(1, minsize=20)

    def __init__(self,master=None):
        tk.Frame.__init__(self, master)
        self.parent = master
        self["relief"] = "sunken"
        self["borderwidth"] = "2"
        
        self.first = True
        self.crcOut = tk.StringVar()
        self.crcOut.set(" ")

        self.crcLabels = []
        self.polynomLabels = []
        self.crc = []
        self.autorun = False

        self.init_centeredFrame()
        
        self.create_help_button()

        self.widgets = False
        
